package com.zxw.设计模式.创建型.单例模式.饿汉式;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @projectName: util-cloud
 * @package: com.zxw.设计模式.创建型.单例模式.饿汉式
 * @className: Test
 * @author: zhangxuewei
 * @description: 测试饿汉模式
 * @date: 2023/6/9 17:33
 * @version: 1.0
 */
public class TestSingletonHungry {

    public static void testMethod() {
        SingletonHungry s = SingletonHungry.getSingletonHungry();
        System.out.println(s.getName());
    }

    /**
     * 反射创建单例破坏 单例模式
     * 解决办法：在构造方法中判断对象是否为空
     */
    public static void reflexCreateSingleto() {
        try {
            Class<SingletonHungry> clazz = SingletonHungry.class;
            Constructor constructor = clazz.getDeclaredConstructor(null);
            constructor.setAccessible(true);
            Object instance1 = constructor.newInstance();
            Object instance2 = constructor.newInstance();
            System.out.println(instance1 == instance2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        testMethod();
        reflexCreateSingleto();
    }
}
